﻿/// <reference path="~/Scripts/jquery-1.4.1.js"/>
/// <reference path="../../Scripts/jquery-ui-1.8.4.custom.min.js" />

//这个属性由页面动态设置数据
var im_materials = [];

$(function () {
	$("#im_materialsSelctionPanel").hide();
	_im_bindAll();
});

function im_findMaterial(materialId) {
	var item = im_findItem(materialId);
	return item != null ? item.material : null;
}

function im_findItem(materialId) {
	for (var i = 0; i < im_materials.length; i++) {
		var bigCate = im_materials[i];
		for (var j = 0; j < bigCate.subCates.length; j++) {
			var subCate = bigCate.subCates[j];
			for (var z = 0; z < subCate.materials.length; z++) {
				var m = subCate.materials[z];
				if (m.value == materialId) {
					return {
						"bigCate": bigCate,
						"cate": subCate,
						"material": m
					};
				}
			}
		}
	}
	return null;
}

function popupMaterials(selectedHandler, selectedMaterialId) {
	$("#im_materialsSelctionPanel").dialog({
		show: 'fold',
		hide: 'fold',
		width: 600,
		height: 150,
		title: '选择物料',
		modal: true
	});
	_im_materialSelectionChanged = selectedHandler;

	if (selectedMaterialId > 0) {
		_im_selectMaterial(selectedMaterialId);
	}
}

function _im_selectMaterial(selectedMaterialId) {
	var m = im_findMaterial(selectedMaterialId);
	if (m != null) {
		if (selectedBigCateId > 0) {
			var e = $("#im_bigCates");
			$selectValue(e[0], m.bigCateId);
		}
		if (selectedSubCateId > 0) {
			var e = $("#im_bigCates");
			$selectValue(e[0], m.pid);
		}
	}
}

function _im_bindAll() {
	var e = $("#im_bigCates");
	$bindSelect(e[0], im_materials);
	_im_bindSubCates();
	e.change(_im_bindSubCates);
}

function _im_bindSubCates() {
	var bigCate = $("#im_bigCates");
	var id = $selInt(bigCate[0]);
	for (var i = 0; i < im_materials.length; i++) {
		var bigCate = im_materials[i];
		if (bigCate.value == id) {
			var e = $("#im_cates");
			$bindSelect(e[0], bigCate.subCates);
			e.change(_im_rebindMaterials);
			_im_rebindMaterials();
			return;
		}
	}
}

function _im_rebindMaterials() {
	var subCate = $("#im_cates");
	var id = $selInt(subCate[0]);
	for (var i = 0; i < im_materials.length; i++) {
		var bigCate = im_materials[i];
		for (var j = 0; j < bigCate.subCates.length; j++) {
			var subCate = bigCate.subCates[j];
			if (subCate.value == id) {
				$("#im_materials div").remove();
				var parent = $("#im_materials");
				$.each(subCate.materials, function (i, m) {
					var htmlSegment = '\
<div>\
	<a href="javascript:;" onclick="_im_materialSelected(' + m.value + ')">' + m.text + '</a>\
</div>';
					parent.append(htmlSegment);
				});
				return;
			}
		}
	}
}

function _im_materialSelected(id) {
	var m = im_findMaterial(id);
	if (m != null) {
		_im_fireEvent(m);
	}
	$('#im_materialsSelctionPanel').dialog('close');
}

var _im_materialSelectionChanged = null;
function _im_fireEvent(material) {
	_im_materialSelectionChanged(material);
}